package review.data.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import review.dao.JobDAO;
import review.entity.Job;

import java.util.Optional;

@Service
@Transactional
public class JobServiceImpl implements JobService {
	@Autowired
	private JobDAO jobDAO;

	public void addJob(Job job) {
		// 检查输入参数
		if (!StringUtils.hasText(job.getName())) {
			throw new RuntimeException("职务名称不能为空！");
		}

		if (jobDAO.findByName(job.getName()) != null) {
			throw new RuntimeException("职务" + job.getName() + "已存在");
		}
		// 定义返回值
		// 业务逻辑
		jobDAO.save(job);
		// 返回
	}

	// 删除
	public void deleteJobs(Integer[] ids) {
		if (ids.length == 0) {
			throw new RuntimeException("未选择职务");
		}
		for (Integer id : ids) {
			if (jobDAO.existsById(id)) {
				jobDAO.deleteById(id);
			} else {
				throw new RuntimeException(String.format("职务ID为：%d的记录未找到", id));
			}
		}
	}

	// 修改
	public void updateJob(Job job) {
		Optional<Job> o = jobDAO.findById(job.getId());
		if (!o.isPresent()) {
			throw new RuntimeException("ID不存在");
		}
		if (jobDAO.findByName(job.getName()) != null) {
			throw new RuntimeException("职务" + job.getName() + "已存在");
		}
		Job j = o.get();
		j.setName(job.getName());
		jobDAO.save(j);
	}

	// 分页模糊查询
	public Page<Job> findAll(int page, int size, Job job) {
		ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreNullValues().withMatcher("name",
				ExampleMatcher.GenericPropertyMatchers.contains());
		Example<Job> example = Example.of(job, matcher);
		Pageable pageable = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.ASC, "id"));
		return jobDAO.findAll(example, pageable);
	}
}
